<template>
  <div>
    <div class="title">
      <span>全部门店</span>
      <div>
        <el-button
          type="primary"
          v-if="userinfo.rolesId == 5"
          @click="synchronizeKoubeiShop()"
          >同步口碑门店</el-button
        >
        <el-button type="primary" :disabled="exxxx" @click="shopExcel"
          ><i class="el-icon-download"></i>导出</el-button
        >
        <el-button
          type="primary"
          v-if="userinfo.rolesId == 5"
          @click="addmendianBtn()"
          >新增门店</el-button
        >
        <el-button icon="el-icon-refresh" @click="refresh"></el-button>
      </div>
    </div>
    <div class="container">
      <div class="screeningBox">
        <div class="leftBox">
          <div class="leftitem">
            <div class="block">
              <el-date-picker
                v-model="date"
                style="width: 60%"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </div>
          </div>
          <div class="leftitem">
            <el-select
              v-model="storesinfo.state"
              style="width: 24%"
              placeholder="门店状态"
            >
              <el-option key="ccc" label="动销" value="1"></el-option>
              <el-option key="zzz" label="未动销" value="0"></el-option>
            </el-select>
            <el-input
              class="merchants"
              style="width: 36%"
              v-model.trim="storesinfo.storesno"
              @keyup.enter.native="soso"
              placeholder="门店名/门店号"
            ></el-input>
          </div>
          <div class="leftitem">
            <el-input
              class="merchants"
              v-if="userinfo.rolesId != 5 && userinfo.rolesId != 6"
              v-model.trim="storesinfo.merchantsno"
              @keyup.enter.native="soso"
              placeholder="商户简称/商户名称/商户号"
            ></el-input>
          </div>
        </div>
        <div class="rightBox">
            <div class="rightitem">
            <el-input
              style="width: 60%"
              v-model.trim="storesinfo.alias"
              @keyup.enter.native="soso"
              placeholder="门店别名"
            ></el-input>
          </div>
        
          <div
            class="rightitem"
            v-if="
              userinfo.rolesId == 1 ||
              userinfo.rolesId == 2 ||
              userinfo.rolesId == 8 ||
              userinfo.rolesId == 9
            "
          >
            <el-form label-width="80px">
             
              <el-autocomplete
                class="servicename"
                v-model.trim="tagname"
                :fetch-suggestions="querySearch_tag"
                @select="serviceid_tag"
                placeholder="标签名称"
                :trigger-on-focus="false"
              ></el-autocomplete>
            </el-form>
          </div>
          <div class="rightitem">
            <el-button icon="el-icon-search" type="primary" @click="soso"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" type="primary" @click="reset"
              >重置</el-button
            >
          </div>
        </div>
      </div>
      <div class="statistical">
        <div class="statisticalitem">
          <div>总门店数</div>
          <div>
            <span class="red">{{ shopnum.total }}</span> 家
          </div>
        </div>
        <div class="statisticalitem">
          <div>动销门店数</div>
          <div>
            <span class="red">{{ shopnum.active }}</span> 家
          </div>
        </div>
      </div>
      <div class="tableBox">
        <el-table
          ref="multipleTable"
          :data="merchantarr"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          stripe
          :header-cell-style="tableHeaderColor"
          v-loading="loading"
        >
          <el-table-column
            type="index"
            align="center"
            label="序号"
          ></el-table-column>
          <el-table-column type="selection"></el-table-column>
          <el-table-column
            prop="shopNo"
            align="center"
            label="门店号"
          ></el-table-column>
          <el-table-column
            prop="shopName"
            align="center"
            label="门店名"
          ></el-table-column>
          <el-table-column
            prop="merchantNo"
            align="center"
            label="商户号"
          ></el-table-column>
          <el-table-column
            prop="merchantShortName"
            align="center"
            label="商户简称"
          ></el-table-column>
          <el-table-column
            prop="alias"
            align="center"
            label="门店别名"
          ></el-table-column>
          <el-table-column
            prop="createTime"
            align="center"
            label="创建时间"
          ></el-table-column>
          <el-table-column align="center" label="门店状态">
            <template slot-scope="scope">
              <div
                type="text"
                v-if="scope.row.activityStatus == 1"
                size="small"
                style="color: green"
              >
                动销
              </div>
              <div
                type="text"
                v-else-if="scope.row.status == 98"
                size="small"
                style="color: red"
              >
                停用
              </div>
              <div type="text" v-else class="red" size="small">未动销</div>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            align="center"
            label="操作"
            width="120"
          >
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="storeinfo(scope.row)"
                >详情</el-button
              >
              <!-- <el-button type="text" size="small" @click="details(scope.row)">修改</el-button> -->
              <el-button
                v-if="scope.row.status != 98"
                type="text"
                size="small"
                @click="shopblockup(scope.row.id)"
                >停用</el-button
              >
              <el-button
                v-if="scope.row.status == 98"
                type="text"
                size="small"
                @click="shopopen(scope.row.id)"
                >启用</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="shopdelete(scope.row.id)"
                >注销</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            @current-change="handleCurrentChange"
            @size-change="sizechange"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="combined"
            :current-page.sync="cur_page"
          ></el-pagination>
        </div>
      </div>
      <br />
      <br />
      <el-dialog
        v-dialogDrag
        title="新增门店"
        :visible.sync="addmendianBox"
        width="60%"
        :close-on-click-modal="false"
      >
        <el-form
          :model="addmendians"
          status-icon
          ref="addmendians"
          label-width="125px"
          class="demo-dynamic store-detail"
        >
          <div class="detail-item">
            <el-form-item :required="true" label="门店名称">
              <el-input
                class="store-input"
                type="text"
                v-model="addmendians.name"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item :required="true" label="门店电话">
              <el-input
                class="store-input"
                type="text"
                v-model="addmendians.phone"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item :required="true" label="门店地址">
              <el-input
                class="store-input"
                type="text"
                v-model="addmendians.address"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item :required="true" label="联系人">
              <el-input
                class="store-input"
                type="text"
                v-model="addmendians.contact"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item :required="true" label="联系人手机号">
              <el-input
                class="store-input"
                type="text"
                v-model="addmendians.contactphone"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="门店类型描述">
              <el-input
                class="store-input"
                type="text"
                v-model="addmendians.udfType"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="入账账户名">
              <el-input
                class="store-input"
                type="text"
                v-model="addmendians.udfAccount"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="门店别名">
              <el-input
                class="store-input"
                type="text"
                v-model="addmendians.alias"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </div>

          <div class="detail-item">
            <el-form-item label="微信子商户号">
              <el-input
                class="store-input"
                type="text"
                v-model="addmendians.wxMchId"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="微信子商户appid">
              <el-input
                class="store-input"
                type="text"
                v-model="addmendians.wxAppid"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="微信订单优惠标记">
              <el-input
                class="store-input"
                type="text"
                v-model="addmendians.wxGoodsTag"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="银联子商户号">
              <el-input
                class="store-input"
                type="text"
                v-model="addmendians.mchUniNo"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="银联终端号">
              <el-input
                class="store-input"
                type="text"
                v-model="addmendians.bank"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="支付宝门店ID">
              <el-input
                class="store-input"
                type="text"
                v-model.trim="addmendians.aliShopId"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="支付宝授权令牌">
              <el-input
                class="store-input"
                type="text"
                v-model.trim="addmendians.aliSpmerToken"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="龙支付柜台号">
              <el-input
                class="store-input"
                type="text"
                v-model.trim="addmendians.longpayPostId"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="龙支付公钥">
              <el-input
                class="store-input"
                type="textarea"
                rows="2"
                v-model.trim="addmendians.longpayPublicKey"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="数币终端号">
              <el-input
                class="store-input"
                type="text"
                v-model.trim="addmendians.ecnyTermId"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </div>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addmendianBox = false">取消</el-button>
          <el-button type="primary" @click="addshopfun()">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  shop,
  getTotalShopCount,
  shopenable,
  shopupdate,
  shopdelete,
  synchronizeKoubeiShop,
  addshop,
  getlabelTagList,
  getDimensionTagList,
  shopdeletes,
  shopExcel,
} from "@/api/api";
export default {
  name: "baseform",
  data: function () {
    return {
      exxxx: false,
      cur_page: 1,
      cur_size: 10,
      visible: false,
      visibles: false,
      addmendianBox: false,
      loading: true,
      multipleSelection: [],
      merchantarr: [],
      pageCount: "",
      date: "",
      userinfo: "",
      shopnum: {
        total: "",
        active: "",
      },
      combined: 0,
      storesinfo: {
        stardate: "",
        enddate: "",
        storesno: "",
        merchantsno: "",
        state: "",
        alias: "",
      },
      addmendians: {
        name: "",
        phone: "",
        address: "",
        contact: "",
        contactphone: "",
        mchUniNo: "",
        wxMchId: "",
        wxAppid: "",
        udfType: "",
        udfAccount: "",
        bank: "",
        alias: "",
        aliShopId: "",
        aliSpmerToken: "",
        longpayPostId: "",
        longpayPublicKey: "",
        wxGoodsTag: "",
        ecnyTermId: "",
      },
      addmendian: {
        name: "",
        address: "",
        contact: "",
        contactphone: "",
        bank: "",
        id: "",
      },
      dimension: "", //选择维度
      tagname: "", //标签名
      label_all: [], //标签模糊查询
      tagId: "",
    };
  },
  created() {
    this.userinfo = JSON.parse(sessionStorage.getItem("userInfo"));
    this.shop();
  },
  mounted() {},
  methods: {
    //修改thead 背景色
    tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return "background-color: #F0F0F0;font-weight: 500;font-size:14px;color:#000;";
      }
    },
    onSubmit() {
      this.$message.success("提交成功！");
    },
    renderheader(h, { column, $index }) {
      return h("span", {}, [
        h("span", {}, column.label.split("?")[0]),
        h("br"),
        h("span", {}, column.label.split("?")[1]),
      ]);
    },
    // 分页导航
    handleCurrentChange(val) {
      this.cur_page = val;
      this.shop();
      this.$nextTick(() => {
        document.querySelectorAll(".content")[0].scrollTop = "0";
      });
    },
    // 分页数量
    sizechange(val) {
      this.cur_size = val;
      this.shop();

      this.$nextTick(() => {
        document.querySelectorAll(".content")[0].scrollTop = "0";
      });
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    joinmerchantsinfo() {
      this.$router.push({ path: "/merchantsinfo" });
    },
    // 门店列表
    shop() {
      shop({
        page: this.cur_page,
        size: this.cur_size,
        mchKeywords: this.storesinfo.merchantsno,
        keywords: this.storesinfo.storesno,
        startTime: this.date[0],
        finishTime: this.date[1],
        activityStatus: this.storesinfo.state,
        tagId: this.tagId,
        alias: this.storesinfo.alias,
      }).then((res) => {
        // console.log(res);
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else if(res.code == 200){
          this.merchantarr = res.data;
          this.combined = res.pageInfo.recordCount;
          this.pageCount = res.pageInfo.pageCount;
          this.loading = false;
        }else{
          this.$message.error(res.message);
          this.loading = false
        }
      });
      // 门店总数
      getTotalShopCount({
        page: this.cur_page,
        size: this.cur_size,
        mchKeywords: this.storesinfo.merchantsno,
        keywords: this.storesinfo.storesno,
        startTime: this.date[0],
        finishTime: this.date[1],
        activityStatus: this.storesinfo.state,
        tagId: this.tagId,
        alias: this.storesinfo.alias,
      }).then((res) => {
        // console.log(res);
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else if(res.code == 200) {
          this.shopnum = res.data;
        }
      });
    },
    // 导出
    shopExcel() {
      this.exxxx = true;
      let i = 0;
      let time = setInterval(() => {
        if (i == 60) {
          loading.close();
          this.$message.error("请求超时");
          clearInterval(time);
        } else {
          i++;
        }
      }, 1000);
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      shopExcel({
        page: this.cur_page,
        size: this.cur_size,
        mchKeywords: this.storesinfo.merchantsno,
        keywords: this.storesinfo.storesno,
        startTime: this.date[0],
        finishTime: this.date[1],
        activityStatus: this.storesinfo.state,
        tagId: this.tagId,
      }).then((res) => {
        if (res.data.code == 405) {
          clearInterval(time);
          sessionStorage.removeItem("token");
          this.$router.push("/login");
          loading.close();
          this.exxxx = false;
        } else if (res.data.code == 200) {
          clearInterval(time);
          let elink = document.createElement("a");
          elink.download = "我的商户.xls";
          elink.href = res.data.data;
          elink.click();
          loading.close();
          this.exxxx = false;
        } else {
          clearInterval(time);
          this.$message.error(res.data.message);
          loading.close();
          this.exxxx = false;
        }
      });
    },
    // 搜索
    soso() {
      if(this.date == null || this.date.length == 0 || this.date == undefined) {
        this.date = []
      }
      this.loading = true;
      this.cur_page = 1;
      this.shop();
    },
    // 重置
    reset() {
      this.storesinfo.merchantsno = "";
      this.storesinfo.storesno = "";
      this.storesinfo.stardate = "";
      this.storesinfo.enddate = "";
      this.storesinfo.state = "";
      this.cur_page = 1;
      this.date = "";
      this.dimension = "";
      this.tagname = "";
      this.tagId = "";
      this.storesinfo.alias = "";
    },
    // 刷新
    refresh() {
      // this.$router.replace({
      //   path: '/refresh',
      //   query: {
      //     t: Date.now()
      //   }
      // })
      this.loading = true;
      this.reset();
      this.shop();
    },

    // 注销门店
    shopdelete(val) {
      this.$confirm("是否确定注销？如确定，该门店将被移除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          shopdelete({}, val).then((res) => {
            // console.log(res);
            if (res.code == 405) {
              sessionStorage.removeItem("token");
              this.$router.push("/login");
            } else if (res.code == 200) {
              this.$message({
                message: "已注销",
                type: "success",
              });
              this.soso();
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 同步口碑门店
    synchronizeKoubeiShop() {
      synchronizeKoubeiShop({}).then((res) => {
        console.log(res);
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
          if (res.code == 200) {
            this.$message({
              message: "同步成功",
              type: "success",
            });
            this.shop();
          } else {
            this.$message.error(res.message);
          }
        }
      });
    },
    // 新增门店box
    addmendianBtn() {
      this.addmendianBox = true;
    },
    // 确定新增门店
    // 增加门店
    addshopfun() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      addshop({
        merchantId: this.userinfo.fid,
        shopName: this.addmendians.name,
        shopTel: this.addmendians.phone,
        shopAddress: this.addmendians.address,
        managerName: this.addmendians.contact,
        managerMobile: this.addmendians.contactphone,
        terminalNoUni: this.addmendians.bank,
        aliShopId: this.addmendians.aliShopId,
        aliSpmerToken: this.addmendians.aliSpmerToken,
        longpayPostId: this.addmendians.longpayPostId,
        longpayPublicKey: this.addmendians.longpayPublicKey,
        wxGoodsTag: this.addmendians.wxGoodsTag,
        ecnyTermId: this.addmendians.ecnyTermId,
        mchUniNo: this.addmendian.mchUniNo,
        wxMchId: this.addmendian.wxMchId,
        wxAppid: this.addmendian.wxAppid,
        udfType: this.addmendian.udfType,
        udfAccount: this.addmendian.udfAccount,
        userId: 1,
        alias: this.addmendians.alias,
        instno: sessionStorage.getItem("instNo"),
        key: sessionStorage.getItem("key"),
      }).then((res) => {
        if (res.code == 200) {
          loading.close();
          this.$message({
            message: "新增成功",
            type: "success",
          });
          this.addmendianBox = false;
          this.refresh();
        } else {
          this.$message.error(res.message);
          loading.close();
        }
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
        }
      });
    },
    //门店详情
    storeinfo(val) {
      // console.log(val)
      this.$router.push({
        path: "/storesinfo",
      });
      sessionStorage.setItem("store_id", JSON.stringify(val.id));
      sessionStorage.setItem("store_shopName", JSON.stringify(val.shopName));
      sessionStorage.setItem("store", JSON.stringify(val));
    },
    //维度查询标签
    // dimension_menu(v){
    //   this.label_all = []
    //   getDimensionTagList({
    //     roleId: v
    //   }).then(res => {
    //     if(res.code == 405){
    //       sessionStorage. removeItem('token')
    //       this.$router.push('/login');
    //     }else if(res.code == 200){
    //       for(var i=0;i<res.data.length;i++){
    //         this.label_all.push({'value':res.data[i].tagName,'id':res.data[i].tagId})
    //       }
    //     }else{
    //       this.$message.error(res.message);
    //     }
    //   })
    // },
    //标签模糊
    querySearch_tag(queryString, cb) {
      let that = this;
      getDimensionTagList({
        roleId: 6,
        tagwords: this.tagname,
      }).then((res) => {
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          that.$router.push("/login");
        } else if (res.code == 200) {
          that.label_all = [];
          for (var i = 0; i < res.data.length; i++) {
            that.label_all.push({
              value: res.data[i].tagName,
              id: res.data[i].tagId,
            });
          }
          let servicearr = that.label_all;
          let results = queryString
            ? servicearr.filter(that.createFilter(queryString))
            : servicearr;
          // 调用 callback 返回建议列表的数据
          cb(results);
        } else {
          that.$message.error(res.message);
        }
      });
    },
    serviceid_tag(item) {
      console.log(item);
      this.tagId = item.id;
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    // 停用门店
    shopblockup(id) {
      this.$confirm("是否确定停用？如确定，该门店将被停用", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          shopdeletes({}, id).then((res) => {
            // console.log(res);
            if (res.code == 405) {
              sessionStorage.removeItem("token");
              this.$router.push("/login");
            } else if (res.code == 200) {
              this.$message({
                message: "已停用",
                type: "success",
              });
              this.soso();
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 启用门店
    shopopen(id) {
      shopenable({}, id).then((res) => {
        console.log(res);
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
          if (res.code == 200) {
            this.$message({
              message: "启用成功",
              type: "success",
            });
            this.visible = false;
            this.soso();
          } else {
            this.$message.error(res.message);
          }
        }
      });
    },
  },
};
</script>
<style scoped lang="less">
.title {
  background: #fff;
  padding: 10px 10px;
  font-size: 18px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
}
.name {
  width: 25%;
}
.screeningBox {
  width: 100%;
  display: flex;
}
.leftBox,
.rightBox {
  width: 50%;
  padding: 0 15px;
  box-sizing: border-box;
}
.leftBox > .leftitem {
  margin-bottom: 15px;
}
.rightBox > .rightitem {
  margin-bottom: 15px;
}
.merchants {
  width: 36%;
}
.statistical {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #00152a;
  color: #fff;
  padding: 12px;
  box-sizing: border-box;
}
.statistical > .statisticalitem {
  width: 50%;
  text-align: center;
  line-height: 200%;
}
.tableBox {
  margin-top: 20px;
}
.store-input{
  width: 95%;
}
.red {
  color: #f9607d;
}

.store-detail {
  display: flex;
}

.detail-item {
  flex: 1;
}

.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
.servicename {
  width: 50%;
}
</style>